/**
 * 加载当前分析主题下的所有流程信息
 */
window.loadAnalyseThemeAll = function loadAnalyseThemeAll(publishObjService, analyseId) {
    var progressbar = $("<div/>").tempoprogressbar();

    $.ajax({
        url: contextPath + "/api/ai/app/listmineresouce?themeId=" + analyseId + "&time=" + new Date().getTime(),
        // data:{
        // 	themeId: analyseId
        // },
        dataType: 'json',
        type: 'get',
        success: function (result) {
            $.ajax({
                url: window.location.origin + "/gateway/cloud-carving-pazq/api/processApproval/getFilterTaskList",
                data:{
                	miningId: analyseId
                },
                dataType: 'json',
                type: 'post',
                success: function (res) { 
                    publishObjService.initAllFlowGrid(result,res);
                    progressbar.tempoprogressbar("destroy");
                }
            })
        }
    });
}

window.MinePublishObjController = function MinePublishObjController(analyseId) {
    this.analyseId = analyseId;
    var topThis = this;

    this.oldtagFormater = function (obj, grid, rows, state) {
        if (rows.oldtag && rows.oldtag == "DONE") {
            return "<div class = 'isoldtag'></div>"
        }
    }

    this.dateFormater = function (obj, grid, rows, state) {
        if (obj && $.isNumeric(obj)) {
            return DateUtils.formatDateTime(new Date(obj), 'yyyy-MM-dd HH:mm:ss');
        }
        return '';
    }

    this.pubDateFormater = function (obj, grid, rows, state) {
        if (rows && rows.AIPUBSTATUS == 0) {
            return "";
        }
        if (obj && $.isNumeric(obj)) {
            return DateUtils.formatDateTime(new Date(obj), 'yyyy-MM-dd HH:mm:ss')
        }
        return '';
    }

    this.backcommitdisinfoFormater = function (obj, grid, rows, state) {
        if (rows.AIPUBSTATUS == 2) {
            return "<span class='backcommit' id='theme_back_icon'></span><span class='unpublished_name'>" + rows.name + "</span>";
        } else {
            return "<span class='unpublished_name' style='margin-right:0px'>" + rows.name + "</span>";
        }
    }

    this.pubAuthorFormater = function (obj, grid, rows, state) {
        if (rows && rows.AIPUBSTATUS == 0) {
            return "";
        } else {
            if (obj) {
                return obj;
            } else {
                return "";
            }
        }
    }

    //更新提示按钮
    this.updateTipBTn = [{
        id: "updatetip",
        icon: 'tempo-ui-icon-flow-update-tip',
        title: TempoUtils.locale("aiview.upgradetip"),
        beforeAdd: function (rowId, rowData, btn) {
            if (rowData.PUBLISHTIME - rowData.lastUpdated >= 0) {
                return false
            }
        },
        click: function (e, dt) {
            var row = dt.rowData;
            topThis.viewInsight(row.obid);
        }
    }];

    //发布按钮列表
    this.publishBtns = [{
        id: "publish",
        icon: 'ui-icon tempo-ui-icon tempo-ui-icon-publish',
        title: TempoUtils.locale("mine.publish-all-flow-grid-optpublish"),
        click: function (e, dt) {
            // 禁用列表按钮的点击事件
//				this.find(".tempo-datagrid-actionbtn").remove();
            $(this).off("click");
            var row = dt.rowData;
            //发布
            if (row.AIPUBSTATUS == "2") {
                topThis.callbackpublishFlow(row.id, row.obid, row.name)
            } else {
                topThis.publishFlow(row.id, row.name)
            }
        }
    }];

    //表格按钮列表
    this.gridBtns = [
        // {
        //     id: "pushService",
        //     icon: "tempo-datagrid-icon ui-icon tempo-ui-icon tempo-ui-icon-sync",
        //     title: TempoUtils.locale("aiview.sync"),
        //     beforeAdd: function (rowId, rowData, btn) {
        //         if (rowData.PUBLISHTIME - rowData.lastUpdated >= 0) {
        //             return false
        //         }
        //         if (rowData.oldtag == "DONE") {
        //             return false
        //         }
        //         return rowData.AIPUBSTATUS != 2
        //     },
        //     click: function (e, dt) {
        //         var progressbar = $("<div/>").tempoprogressbar();
        //         var row = dt.rowData;
        //         if (row.PUBLISHTIME - row.lastUpdated >= 0) {
        //             progressbar.tempoprogressbar("destroy");
        //             topThis.infoTip(TempoUtils.locale("aiview.service_isnew"));
        //         } else {
        //             //同步
        //             $.ajax({
        //                 url: contextPath + "/api/ai/app/service/sync",
        //                 data: {//传值为流程id Object的id
        //                     id: row.id,
        //                     obid: row.obid
        //                 },
        //                 dataType: 'json',
        //                 type: 'post',
        //                 success: function (rs) {
        //                     progressbar.tempoprogressbar("destroy");
        //                     if (rs.success) {
        //                         Eventbus.trigger("reloadPubTree.ai-theme", analyseId);
        //                         if (rs.data) {
        //                             topThis.infoTip(TempoUtils.locale("mine.syncAndStreamTipData"));
        //                         } else {
        //                             topThis.infoTip(TempoUtils.locale("aiview.sync") + TempoUtils.locale("aiview.cg"));
        //                         }
        //                         Eventbus.trigger('aiview.pub.initgrid');
        //                     } else {
        //                         topThis.infoTip(rs.message);
        //                     }
        //                 }
        //             });
        //         }

        //     }
        // },
         {
            id: "unpushService",
            icon: "tempo-datagrid-icon tempo-datagrtempo-datagrid-icon o-datagrid-actionbtn ui-icon tempo-ui-icon tempo-ui-icon-publish-cancel",
            title: TempoUtils.locale("aiview.async-cancel"),
            beforeAdd: function (rowId, rowData, btn) {
                if (rowData.appId == null) {
                    return false
                }
                return rowData.AIPUBSTATUS != 2
            },
            click: function (e, dt) {
                var row = dt.rowData;
                //取消发布
                topThis.unpublishFlow(row.id, row.obid)
            }
        }
    ];

    //列模型-已发布
    var colsModel = [{
        name: 'id',
        index: 'id',
        hidden: true,
    }, {
        name: 'appId',
        index: 'appId',
        hidden: true,
    }, {
        name: 'parentId',
        index: 'parentId',
        hidden: true
    }, {
        name: 'obid',
        index: 'obid',
        hidden: true,
    }, {
        name: 'author',
        index: 'author',
        hidden: true,
    }, {
        name: 'createTime',
        index: 'createTime',
        hidden: true,
        formatter: this.dateFormater
    }, {
        name: 'lastUpdated',
        index: 'lastUpdated',
        hidden: true,
        formatter: this.dateFormater
    }, {
        name: 'PUBAUTHOR',
        index: 'PUBAUTHOR',
        hidden: true,
    }, {
        name: '',
        index: '',
        align: 'center',
        resizable: false,
        sortable: false,
        width: 30,
        // buttons: this.updateTipBTn,
        hidden: true
    }, {
        name: 'name',
        index: 'name',
        align: 'center',
        resizable: false,
        sortable: false,
        formatter: function (obj, grid, rows, state) {
            return '<span>' + obj + '</span>';
        }
    }, {
        name: 'publishname',
        index: 'publishname',
        hidden: true,
    }, {
        name: 'serviceType',
        index: 'serviceType',
        align: 'center',
        resizable: false,
        sortable: false,
        formatter: function (obj, grid, rows, state) {
            if (obj) {
                switch (obj) {
                    case "async":
                        return TempoUtils.locale("aiview.async_service")
                        break;
                    case "sync":
                        return TempoUtils.locale("aiview.sync_service")
                        break;
                    case "stream":
                        return TempoUtils.locale("aiview.stream_service")
                        break;
                }
            }
            return "";
        }
    }, {
        name: 'AIPUBSTATUS',
        index: 'AIPUBSTATUS',
        align: 'center',
        hidden: true,
    }, {
        name: 'PUBLISHTIME',
        index: 'PUBLISHTIME',
        align: 'center',
        width: 200,
        sortable: false,
        formatter: this.pubDateFormater
    }, {
        name: 'oldtag',
        index: 'oldtag',
        hidden: true,
        formatter: this.oldtagFormater
    }, {
        name: '',
        index: '',
        align: 'center',
        resizable: false,
        sortable: false,
        buttons: this.gridBtns
    }];

    //列模型-未发布
    var colsModel2 = [{
        name: 'id',
        index: 'id',
        hidden: true
    }, {
        name: 'appId',
        index: 'appId',
        hidden: true,
    }, {
        name: 'parentId',
        index: 'parentId',
        hidden: true
    }, {
        name: 'obid',
        index: 'obid',
        hidden: true,
    }, {
        name: 'author',
        index: 'author',
        hidden: true,
    }, {
        name: 'PUBLISHTIME',
        index: 'PUBLISHTIME',
        hidden: true,
        formatter: this.pubDateFormater
    }, {
        name: 'createTime',
        index: 'createTime',
        hidden: true,
        formatter: this.dateFormater
    }, {
        name: 'lastUpdated',
        index: 'lastUpdated',
        hidden: true,
        formatter: this.dateFormater
    }, {
        name: 'serviceType',
        index: 'serviceType',
        hidden: true,
        formatter: function (obj, grid, rows, state) {
            if (obj) {
                switch (obj) {
                    case "async":
                        return TempoUtils.locale("aiview.async_service")
                        break;
                    case "sync":
                        return TempoUtils.locale("aiview.sync_service")
                        break;
                    case "stream":
                        return TempoUtils.locale("aiview.stream_service")
                        break;
                }
            }
            return "";
        }
    }, {
        name: 'name',
        index: 'name',
        align: 'center',
        hidden: true,
    }, {
        name: 'flowname',
        index: 'flowname',
        align: 'center',
        width: 200,
        title: false,
        resizable: false,
        sortable: false,
        formatter: this.backcommitdisinfoFormater
    }, {
        name: 'AIPUBSTATUS',
        index: 'AIPUBSTATUS',
        align: 'center',
        hidden: true,
    }, {
        name: 'AIBACKCOMMENT',
        index: 'AIBACKCOMMENT',
        hidden: true,
    }, {
        name: '',
        index: '',
        width: 80,
        align: 'center',
        resizable: false,
        buttons: this.publishBtns
    }];

    /**
     * 初始化全部流程列表
     */
    this.initAllFlowGrid = function (data,filterD) {
        let publishD = []
        if (filterD.data.length <= 0) {
            publishD = data
        } else {
            if (data.length > 0) {
                let set = filterD.data.map(item=>item.modelId)
                publishD = data.filter(item=>!set.includes(item.appId))
            }
        }
        if (!this.publishedflowGrid) {
            this.publishedflowGrid = $('#ai-mine-published-all-grid').datagrid({
                datatype: "local",
                data: publishD,
                height: 290,
                width: 525,
                rownumbers: false,
                hidegrid: false,
                resizable: false,
                striped: true,
                viewrecords: true,
                loadui: 'disable',
                multiselect: true,
                pagination: false,
                colNames: ['id',
                    'appId',
                    'parentId',
                    'obid',
                    'author',
                    'createTime',
                    'lastUpdated',
                    'PUBAUTHOR',
                    '',
                    TempoUtils.locale("aiview.flowname"),
                    'publishname',
                    TempoUtils.locale("aiview.service-type"),
                    TempoUtils.locale("aiview.column-aipubstatus"),
                    TempoUtils.locale("aiview.publish_sync_time"),
                    'oldtag',
                    TempoUtils.locale("aiview.opt")],
                colModel: colsModel
            });
        }

        if (!this.unpublishedflowGrid) {
            this.unpublishedflowGrid = $('#ai-mine-unpublished-all-grid').datagrid({
                datatype: "local",
                data: publishD,
                height: 290,
                width: 280,
                rownumbers: false,
                hidegrid: false,
                resizable: false,
                striped: true,
                viewrecords: true,
                loadui: 'disable',
                multiselect: true,
                pagination: false,
                colNames: ['id',
                    'appId',
                    'parentId',
                    'obid',
                    'author',
                    'PUBLISHTIME',
                    'createTime',
                    'lastUpdated',
                    'serviceType',
                    'name',
                    TempoUtils.locale("aiview.name"),
                    TempoUtils.locale("aiview.column-aipubstatus"),
                    'AIBACKCOMMENT',
                    TempoUtils.locale("aiview.opt")],
                colModel: colsModel2
            });
        }

        this.unpublishedflowGrid.jqGrid('clearGridData');
        this.publishedflowGrid.jqGrid('clearGridData');


        $(".app-unpublish-gridPanel").find(".ui-th-div").first().find("input").prop("checked", false);
        $(".app-publish-gridPanel").find(".ui-th-div").first().find("input").prop("checked", false);
        var publishedNum = 0;
        var unpublishedNum = 0;
        if (publishD && publishD.length > 0) {
            //退回信息置顶显示
            for (var i = publishD.length - 1; i >= 0; i--) {
                if (publishD[i].AIPUBSTATUS == "2") {
                    this.unpublishedflowGrid.jqGrid('addRowData', publishD[i].id, publishD[i], i)
                    unpublishedNum++;
                }
            }
            for (var i = publishD.length - 1; i >= 0; i--) {
                if (publishD[i].AIPUBSTATUS == "1" || publishD[i].oldtag == "DONE") {
                    this.publishedflowGrid.jqGrid('addRowData', publishD[i].obid, publishD[i], i)
                    publishedNum++;
                } else if (publishD[i].AIPUBSTATUS != "2") {
                    this.unpublishedflowGrid.jqGrid('addRowData', publishD[i].id, publishD[i], i)
                    unpublishedNum++;
                }
            }
        }

        //修改标题-流程个数
        $(".ai-publish-flownum").text(TempoUtils.locale("aiview.lp") + publishedNum + TempoUtils.locale("aiview.rp"));
        $(".ai-unpublish-flownum").text(TempoUtils.locale("aiview.lp") + unpublishedNum + TempoUtils.locale("aiview.rp"));

        $(".backcommitdisinfo").hide();
        $(".backcommit").mouseover(function () {
            if (!$(this).find(".backcommitdisinfo").length > 0) {
                var id = $(this).parent().parent().attr('id');
                var datainfo = topThis.unpublishedflowGrid.datagrid("getRowData", id);
                var backcommitInfo = "<div class='backcommitdisinfo' id='disinfo'><div class='backcommitdisinfoContent'><span>" + datainfo.PUBLISHTIME + "</span><br/><span style='color:#555555'>" + datainfo.AIBACKCOMMENT + "</span></div></div>"
                $(backcommitInfo).appendTo($(this));
            } else {
                $(this).find(".backcommitdisinfo").show();
            }
        })
        $(".backcommit").mouseout(function () {
            $(this).parent().find(".backcommitdisinfo").hide();
        })

        $("#flowtip").mouseover(function () {
            $("#flowtip-message").text(TempoUtils.locale("aiview.flowtip"));
        })
        $("#flowtip").mouseout(function () {
            $("#flowtip-message").text("");
        })


        $('td[aria-describedby=ai-mine-unpublished-all-grid_flowname]').find(".unpublished_name").mouseover(function () {
            if (!$(this).find("#detailInfo").length > 0) {
                var id = $(this).parent().parent().attr('id');
                var datainfo = topThis.unpublishedflowGrid.datagrid("getRowData", id);
                var disinfo = "<div id='detailInfo'>" +
                    "<div style='margin-top: 10px;margin-bottom: 25px;padding-top: 5px;'><span style='float: left;margin-left: 22px;color: black;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;max-width: 225px;' title='" + datainfo.name + "'>" + datainfo.name + "</span></div>" +
                    "<div><table id='detailInfoTable'>" +
                    "<tr><td>" + TempoUtils.locale("aiview.creator") + TempoUtils.locale("mine.split_char_colon") + "</td><td class='tempo-detailInfo-name-label'>" + datainfo.author + "</td></tr>" +
                    "<tr><td>" + TempoUtils.locale("aiview.create_time") + TempoUtils.locale("mine.split_char_colon") + "</td><td>" + datainfo.createTime + "</td></tr>" +
                    "<tr><td>" + TempoUtils.locale("aiview.update_time") + TempoUtils.locale("mine.split_char_colon") + "</td><td>" + datainfo.lastUpdated + "</td></tr>" +
                    "</table></div>" +
                    "<div class='seeview' id=" + datainfo.id + ">" + TempoUtils.locale("aiview.seeflowview") + "<span class='ui-icon tempo-ui-icon tempo-ui-icon-rightarrows-undertint'></span></div></div>";
                $(disinfo).appendTo($(this));
            } else {
                $(this).find("#detailInfo").show();
            }
            $(".seeview").css("cursor", "pointer");
            //弹框偏移
            var offset = $(".tempo-theme-publish-dialog").offset().top + 280;
            if ($(this).offset().top > offset) {
                $(this).find("#detailInfo").css("margin-top", "-172px");
            }
            var scrollTop = topThis.unpublishedflowGrid.parent().parent().scrollTop()
            if (scrollTop != 0) {
                var sh = -scrollTop;
                $(this).find("#detailInfo").css("margin-top", sh);
                if ($('body').height() - $(this).find("#detailInfo").height() < $(this).find("#detailInfo").offset().top) {
                    $(this).find("#detailInfo").css("margin-top", sh - 180);
                }
            }

            $(".seeview").off("click").on("click", function () {
                var id = $(this).attr("id");
                topThis.viewPublishFlow(id);
            });

        });
        $('td[aria-describedby=ai-mine-unpublished-all-grid_flowname]').find(".unpublished_name").mouseout(function () {
            $(this).find("#detailInfo").css("margin-top", "0px");
            $(this).find("#detailInfo").hide();
        });

        $('td[aria-describedby=ai-mine-published-all-grid_name]').mouseover(function () {
            if (!$(this).find("#detailInfo").length > 0) {
                var id = $(this).parent().attr('id');
                var datainfo = topThis.publishedflowGrid.datagrid("getRowData", id);
                var author = datainfo.author;
                ;
                var pubauthor = datainfo.PUBAUTHOR;
                if (author.length > 16) {
                    author = author.substr(0, 16) + "...";
                }
                if (pubauthor.length > 16) {
                    pubauthor = pubauthor.substr(0, 16) + "...";
                }
                var disinfo = "<div id='detailInfo'><table id='detailInfoTable'><tr><td>" + TempoUtils.locale("aiview.creator") + TempoUtils.locale("mine.split_char_colon") + "</td><td>" + author + "</td></tr>" +

                    "<tr><td>" + TempoUtils.locale("aiview.app_name") + TempoUtils.locale("mine.split_char_colon") + "</td><td class='tempo-detailInfo-name-label'>" + datainfo.publishname + "</td></tr>" +
                    "<tr><td>" + TempoUtils.locale("aiview.create_time") + TempoUtils.locale("mine.split_char_colon") + "</td><td>" + datainfo.createTime + "</td></tr>" +
                    "<tr><td>" + TempoUtils.locale("aiview.update_time") + TempoUtils.locale("mine.split_char_colon") + "</td><td>" + datainfo.lastUpdated + "</td></tr>" +
                    "<tr><td>" + TempoUtils.locale("aiview.column-aipublisher") + TempoUtils.locale("mine.split_char_colon") + "</td><td class='tempo-detailInfo-name-label'>" + pubauthor + "</td></tr>" +
                    "<tr><td>" + TempoUtils.locale("aiview.publish_sync_time") + TempoUtils.locale("mine.split_char_colon") + "</td><td>" + datainfo.PUBLISHTIME + "</td></tr></table><div class='seeview' id=" + datainfo.obid + ">" + TempoUtils.locale("aiview.seeflowview") + "<span class='ui-icon tempo-ui-icon tempo-ui-icon-rightarrows-undertint'></span></div></div>"
                $(disinfo).appendTo($(this));
            } else {
                $(this).find("#detailInfo").show();
            }
            $(".seeview").css("cursor", "pointer");
            //弹框偏移
            var offset = $(".tempo-theme-publish-dialog").offset().top + 250;
            if ($(this).offset().top > offset) {
                $(this).find("#detailInfo").css("margin-top", "-262px");
            }
            var scrollTop = topThis.publishedflowGrid.parent().parent().scrollTop()
            if (scrollTop != 0) {
                var sh = -scrollTop;
                if ($(this).offset().top > offset) {
                    sh = sh - 270;
                }
                $(this).find("#detailInfo").css("margin-top", sh);
            }
            $(".seeview").off("click").on("click", function () {
                var id = $(this).attr("id");
                topThis.viewPublishFlowInsight(id);
            });
        });

        $('td[aria-describedby=ai-mine-published-all-grid_name]').mouseout(function () {
            $(this).find("#detailInfo").css("margin-top", "0px");
            $(this).find("#detailInfo").hide();
        });

        topThis.publishLisener();
    }

    this.initDetailInfo = function () {
        if (rows.serviceType) {
            switch (rows.serviceType) {
                case "async":
                    serviceType = TempoUtils.locale("aiview.async_service")
                    break;
                case "sync":
                    serviceType = TempoUtils.locale("aiview.sync_service")
                    break;
                case "stream":
                    serviceType = TempoUtils.locale("aiview.stream_service")
                    break;
            }
        }

    }

    this.publishLisener = function () {
        //发布
        $("#app-flow-publish").off("click").on("click", function () {
            var checkedRowIds = topThis.unpublishedflowGrid.datagrid("getCheckedRowIds");
            if (checkedRowIds.length > 0) {
                var rowids = [];
                var obids = [];
                var names = [];
                var analyseIds = [];
                for (var i = 0; i < checkedRowIds.length; i++) {
                    var rowid = checkedRowIds[i]
                    var rowData = topThis.unpublishedflowGrid.datagrid("getRowData", rowid)
                    var name = rowData.name
                    if (rowData.AIPUBSTATUS == "2") {
                        topThis.callbackpublishFlow(rowid, rowData.obid, name)
                        continue;
                    }
                    rowids.push(rowid);
                    names.push(name);
                    analyseIds.push(analyseId);
                }
                if (rowids.length > 0) {
                    topThis.batchPublishFlow(rowids, analyseIds, names);
                }
            } else {
                topThis.infoTip(TempoUtils.locale("aiview.chooseflow_tip1"));
            }
        });
        //取消发布
        $("#app-flow-cancel-publish").off("click").on("click", function () {
            var checkedRowIds = topThis.publishedflowGrid.datagrid("getCheckedRowIds");
            if (checkedRowIds.length > 0) {
                var rowids = [];
                var obids = [];
                for (var i = 0; i < checkedRowIds.length; i++) {
                    var obid = checkedRowIds[i]
                    var data = topThis.publishedflowGrid.datagrid("getRowData", obid)
                    var rowid = data.id
                    rowids.push(rowid);
                    obids.push(obid);
                }
                topThis.unPublishFlows(rowids, obids)
            } else {
                topThis.infoTip(TempoUtils.locale("aiview.chooseflow_tip2"));
            }
        });

        //同步
        $("#app-flow-sys").off("click").on("click", function () {
            var checkedRowIds = topThis.publishedflowGrid.datagrid("getCheckedRowIds");
            if (checkedRowIds.length > 0) {
                var rowids = [];
                var obids = [];
                for (var i = 0; i < checkedRowIds.length; i++) {
                    var obid = checkedRowIds[i]
                    var data = topThis.publishedflowGrid.datagrid("getRowData", obid)
                    var rowid = data.id
                    if (data.oldtag && data.oldtag == "DONE") {
                        continue;
                    }
                    //将标准事件转换成时间戳
                    var pt = new Date(data.PUBLISHTIME);
                    var lt = new Date(data.lastUpdated);
                    if (pt.getTime() - lt.getTime() < 0) {
                        rowids.push(rowid);
                        obids.push(obid);
                    }
                }
                if (rowids.length > 0) {
                    topThis.publishsync_service(rowids, obids)
                } else {
                    topThis.infoTip(TempoUtils.locale("aiview.service_isnew"));
                }
            } else {
                topThis.infoTip(TempoUtils.locale("aiview.chooseflow_tip"));
            }
        });

    }
    /**
     * 删除发布
     */
    this.settingServices = function (data) {
        var flowId = data.id;
    }

    /**
     * 查看流程图弹出框增加放大缩小功能
     * @param dialog 弹出框
     */
    this.maxiMizeFunction = function (dialog) {
        //获取到关闭按钮
        var closeButton = dialog.prev().find("button");
        //获取初始化dialog距离顶部和左侧的距离
        var dialogLeft = dialog.parent().css("left");
        var dialogTop = dialog.parent().css("top");
        //获取初始化dialog高度
        var dialogHeight = dialog.height();
        var maximizeButton = $('<button dialogHeight="' + dialogHeight + '" dialogLeft="' + dialogLeft + '" dialogTop="' + dialogTop + '" maximize="min" type="button" ' +
            'class="tempo-button ui-button ui-corner-all ui-widget ui-button-icon-only ui-dialog-titlebar-maximize" ' +
            'id="view-publish-flow-maximize"  title="" style="height: 28px; line-height: 26px;">' +
            '<span class="ui-button-icon ui-icon tempo-ui-icon tempo-ui-icon-window-max"></span><span class="ui-button-icon-space"></span></button>');
        maximizeButton.insertAfter(closeButton);
        maximizeButton.unbind('click').bind('click', function (e) {
            //浏览器宽度
            var windowWidth = $(window).width();
            //浏览器高度
            var windowHeight = $(window).height();
            var maximize = $(this).attr("maximize");
            if (maximize == 'min') {
                //调整整个弹出框距离顶部和左边的距离
                dialog.parent().css("left", "0px");
                dialog.parent().css("top", "0px");
                //调整整个弹出框宽高
                dialog.parent().width(windowWidth);
                dialog.parent().height(windowHeight);
                //调整内部高度
                dialog.height(windowHeight - dialog.prev().height() * 2);
                $(this).attr("maximize", "max");
            } else {
                //调整内部高度
                dialog.height($(this).attr("dialogHeight"));
                //调整整个弹出框宽高
                dialog.parent().css("width", window.screen.width * 0.75);
                dialog.parent().css("height", window.screen.height * 0.7);
                //调整整个弹出框距离顶部和左边的距离
                dialog.parent().css("left", $(this).attr("dialogLeft"));
                dialog.parent().css("top", $(this).attr("dialogTop"));
                $(this).attr("maximize", "min");
            }
        });
    }

    /**
     * 查看流程图
     */
    this.viewPublishFlow = function (id) {
        var width = window.screen.width * 0.75;
        var height = window.screen.height * 0.7;
        var dialog = $('<div style="width:100%;height:100%;"/></div>').attr("id", 'view-publish-flow-' + id);
        dialog.dialog({
            title: topThis.unpublishedflowGrid.datagrid("getRowData", id).name,
            width: width,
            height: height,
            resizable: false,
            close: function () {
                dialog.dialog('destroy');
            },
            open: function () {
                $("<iframe src='" + contextPath + "/api/ai/resource/analyse/view/preview?" +
                    "flowId=" + id + "&&id=" + analyseId + "#" + id + "&&isFlowView=true' style='height: 100%;width: 100%;border: none;'>'></iframe>").appendTo(dialog);
                //增加放大缩小按钮
                topThis.maxiMizeFunction(dialog);
            },
        });
    }

    /**
     * 查看成果洞察图
     */
    this.viewPublishFlowInsight = function (id) {
        var width = window.screen.width * 0.75;
        var height = window.screen.height * 0.7;
        var dialog = $('<div style="width:100%;height:100%;"/></div>').attr("id", 'view-publish-flow-insight-' + id);
        dialog.dialog({
            title: topThis.publishedflowGrid.datagrid("getRowData", id).publishname,
            width: width,
            height: height,
            resizable: false,
            close: function () {
                dialog.dialog('destroy');
            },
            open: function () {
                $("<iframe src='" + contextPath + "/api/ai/app/view/overview?id=" + id + "' style='height: 100%;width: 100%;border: none;'>'></iframe>").appendTo(dialog);
                //增加放大缩小按钮
                topThis.maxiMizeFunction(dialog);
            }
        });
    }

    /**
     * 查看流程洞察图
     */
    this.viewInsight = function (id) {
        var width = window.screen.width * 0.92;
        var left = window.screen.width * 0.03;
        var top = window.screen.height * 0.05;
        var height = window.screen.height * 0.8;
        var url = contextPath + '/api/ai/app/view/overview?id=' + id + "&&mode=false";
        var newWindow = window.open(url, '_newwindow', 'z-look=yes,height=' + height + ',width=' + width + ',left=' + left + ',top=' + top + ',location=no,toolbar=no,menubar=no,scrollbars=yes,resizable=yes')
    }

    /**
     * 批量取消发布
     */
    this.unPublishFlows = function (ids, obids) {
        var progressbar = $("<div/>").tempoprogressbar();
        $.ajax({
            url: window.location.origin + "/gateway/cloud-carving-pazq/api/processApproval/unpublish",
            data: {
                modelId: obids.join(','),
            },
            dataType: 'json',
            type: 'post',
            success: function (result) {
                $.ajax({
                    url: contextPath + "/api/ai/app/batch-unpublish",
                    data: {
                        id: ids,
                        flowObjectId: obids
                    },
                    dataType: 'json',
                    type: 'post',
                    traditional: true,
                    success: function (result) {
                        progressbar.tempoprogressbar("destroy");
                        if (result && result.success) {
                            topThis.infoTip(TempoUtils.locale("aiview.unpublish_success"));
                        } else {
                            topThis.infoTip(TempoUtils.locale("aiview.unpublish_fail") + ":" + result.message);
                        }
                        Eventbus.trigger("reloadPubTree.ai-theme", analyseId);
                        Eventbus.trigger('aiview.pub.initgrid');
                        return;
                    }
                });
            },
            error: function () {
                progressbar.tempoprogressbar("destroy");
                topThis.infoTip(TempoUtils.locale("aiview.unpublish_fail"))
            }
        })
    }

    /**
     * 批量发布
     */
    this.batchPublishFlow = function (flowIds, analyseIds, names) {
        topThis.infoTip(TempoUtils.locale("aiview.publish_success"),[flowIds, analyseIds, names]);
    }
    this.publishSureFlowList = function (flowIds, analyseIds, names) {
        var progressbar = $("<div/>").tempoprogressbar();
        $.ajax({
            url: contextPath + "/api/ai/app/batch-publish",
            data: {
                flowIds: flowIds,
                analyseIds: analyseIds,
                names: names,
            },
            dataType: 'json',
            type: 'post',
            traditional: true,
            success: function (result) {
                Eventbus.trigger('aiview.pub.initgrid');
                progressbar.tempoprogressbar("destroy");
                if (result && result.success) {
                    $.ajax({
                        url: window.location.origin + "/gateway/cloud-carving-pazq/api/processApproval/getAiFlowListData",
                        data: JSON.stringify({
                            flowIds: flowIds.join(','),
                            page: 1,
                            rows: 10,
                            modelType: '0',
                            taskType: '0',
                            orderByMaps: [{orderColumnName: 'publishTime',orderType:'desc'}],
                            modelName: ''
                        }),
                        contentType: 'application/json',
                        dataType: 'json',
                        type: 'post',
                        success: function(res) {
                            var thisUrl = window.location.origin + '/portal/#/OperationAreaIndex/index'
                            parent.location.href = thisUrl;
                        }
                    })
                } else {
                    topThis.infoTip(TempoUtils.locale("aiview.publish_fail") + ":" + result.message);
                }
                Eventbus.trigger("reloadPubTree.ai-theme", analyseId);
            }
        });
    }
    /**
     * 批量同步
     */
    this.publishsync_service = function (ids, obids) {
        var progressbar = $("<div/>").tempoprogressbar();
        $.ajax({
            url: contextPath + "/api/ai/app/service/batch-sync",
            data: {//传值为流程id Object的id
                id: ids,
                obid: obids
            },
            dataType: 'json',
            type: 'post',
            traditional: true,
            success: function (rs) {
                progressbar.tempoprogressbar("destroy");
                if (rs.success) {
                    Eventbus.trigger("reloadPubTree.ai-theme", analyseId);
                    if (rs.data) {
                        topThis.infoTip(TempoUtils.locale("mine.syncAndStreamTipData"));
                    } else {
                        topThis.infoTip(TempoUtils.locale("aiview.sync") + TempoUtils.locale("aiview.cg"));
                    }
                } else {
                    topThis.infoTip(rs.message);
                }
                Eventbus.trigger('aiview.pub.initgrid');
            }
        });
    }


    this.publishFlow = function (id, name) {
        topThis.infoTip(TempoUtils.locale("aiview.publish_success"),[id,name]);

    }
    this.publishSureFlow = function(id, name) {
        var progressbar = $("<div/>").tempoprogressbar();
        //发布
        $.ajax({
            url: contextPath + "/api/ai/app/publish",
            data: {
                flowId: id,
                analyseId: analyseId,
                name: name,
                pubComment: ""
            },
            dataType: 'json',
            type: 'post',
            success: function (result) {
                Eventbus.trigger('aiview.pub.initgrid');
                Eventbus.trigger("reloadPubTree.ai-theme", analyseId);
                progressbar.tempoprogressbar("destroy");
                if (!result || !result.success) {
                    topThis.infoTip(TempoUtils.locale("aiview.publish_fail") + ":" + result.message);
                } else {
                    $.ajax({
                        url: window.location.origin + "/gateway/cloud-carving-pazq/api/processApproval/getAiFlowListData",
                        data: JSON.stringify({
                            page: 1,
                            rows: 10,
                            modelType: '0',
                            flowIds: id,
                            orderByMaps: [{orderColumnName: 'publishTime',orderType:'desc'}],
                            taskType: '0',
                            modelName: ''
                        }),
                        dataType: 'json',
                        contentType: 'application/json',
                        type: 'post',
                        success: function(result1) {
                            var thisUrl = window.location.origin + '/portal/#/OperationAreaIndex/index'
                            parent.location.href = thisUrl;
                        }
                    })
                }
            }
        });
    }
    this.unpublishFlow = function (id, obid) {
        var progressbar = $("<div/>").tempoprogressbar();
        $.ajax({
            url: window.location.origin + "/gateway/cloud-carving-pazq/api/processApproval/unpublish",
            data: {
                modelId: obid,
            },
            dataType: 'json',
            type: 'post',
            success: function () {
                $.ajax({
                    url: contextPath + "/api/ai/app/unpublish",
                    data: {
                        id: id,
                        flowObjectId: obid
                    },
                    dataType: 'json',
                    type: 'post',
                    traditional: true,
                    success: function (result) {
                        progressbar.tempoprogressbar("destroy");
                        if (result && result.success) {
                            Eventbus.trigger("reloadPubTree.ai-theme", analyseId);
                            topThis.infoTip(TempoUtils.locale("aiview.unpublish_success"));
                        } else {
                            if (result.messageCode === "gray") {
                                TempoUtils.showTip("服务已灰度发布,不可取消发布");
                            } else {
                                topThis.infoTip(TempoUtils.locale("aiview.unpublish_fail") + ":" + result.message);
                            }
                        }
                        Eventbus.trigger('aiview.pub.initgrid');
                    }
                });
            },
            error: function() {
                progressbar.tempoprogressbar("destroy");
                topThis.infoTip(TempoUtils.locale("aiview.unpublish_fail"))
            }
        })

    }

    this.callbackpublishFlow = function (id, obid, name) {
        var progressbar = $("<div/>").tempoprogressbar();
        $.ajax({
            url: window.location.origin + "/gateway/cloud-carving-pazq/api/processApproval/unpublish",
            data: {
                modelId: obid,
            },
            dataType: 'json',
            type: 'post',
            success: function() {
                $.ajax({
                    url: contextPath + "/api/ai/app/unpublish",
                    data: {
                        id: id,
                        flowObjectId: obid
                    },
                    async: false,
                    dataType: 'json',
                    type: 'post',
                    traditional: true,
                    success: function (result) {
                        progressbar.tempoprogressbar("destroy");
                        if (result && result.success) {
                            topThis.publishFlow(id, name);
                        } else {
                            topThis.infoTip(TempoUtils.locale("aiview.unpublish_fail") + ":" + result.message);
                        }
                        Eventbus.trigger('aiview.pub.initgrid');
                    }
                });
            },
            error:function () {
                progressbar.tempoprogressbar("destroy");
                topThis.infoTip(TempoUtils.locale("aiview.unpublish_fail"))
            }
        })
    }

    this.infoTip = function (msg,arr) {
        if (arr) {
            $("<div style='word-break: break-all;'/>").confirm({
                msg: msg,
                ok: function() {
                    if (arr.length==2) {
                        topThis.publishSureFlow(arr[0],arr[1])
                    } else {
                        topThis.publishSureFlowList(arr[0],arr[1],arr[2])
                    }
                }
            });
        } else {
            $("<div style='word-break: break-all;'/>").alert({
                msg: msg
            });
        }
    }
}